package com.zhkj.txg.module.mine.ui

import android.app.Dialog
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.ui.ProductListActivity
import com.zhkj.txg.module.home.ui.ShopActivity
import com.zhkj.txg.module.mine.adapter.CouponAdapter
import com.zhkj.txg.module.mine.vm.CouponViewModel
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import com.zhkj.txg.utils.QRCodeUtils
import kotlinx.android.synthetic.main.fragment_collection.*

class CouponListFragment : ViewModelFragment<CouponViewModel>() {

    companion object {
        private val USE_TYPE = "useType"
        private val API_TYPE = "apiType"
        private val STATUS = "status"

        fun newInstance(userType: Int, apiType: Int, status: Int): CouponListFragment {
            return CouponListFragment().apply {
                arguments = bundleOf(
                    Pair(USE_TYPE, userType), Pair(API_TYPE, apiType), Pair(STATUS, status)
                )
            }
        }
    }

    override fun setViewModel(): CouponViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_collection

    private val couponAdapter = CouponAdapter().apply {
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.couponList()
        }
        setOnItemClickListener { _, view, position ->

            layDialog(
                "优惠券号:${data[position].giftcertNo}",
                QRCodeUtils.createQRCodeBitmap(data[position].giftcertNo, 700, 700)
            )
//            when (view.id) {
//                R.id.viewCoupon -> {
//                    data[position].coupon?.shown = data[position].coupon?.shown?.not() ?: false
//                    notifyItemChanged(position)
//                }
//                R.id.tvCouponJump -> data[position].coupon?.let {
//                    if (!it.useType.isNullOrEmpty() && it.params != null) when (it.useType) {
//                        "1" -> ProductDetailActivity.normalProduct(requireContext(), it.params.toInt())
//                        "2" -> ProductListActivity.categoryOpen(
//                            requireContext(),
//                            getString(R.string.coupon),
//                            it.params.toInt()
//                        )
//                        "3" -> ShopActivity.open(requireContext(), "", it.params.toInt())
//                    }
//                }
//            }
        }
    }

    override fun initData() {
        viewModel.couponList()
    }

    override fun initUI() {
        with(rvCollection) {
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            layoutManager = LinearLayoutManager(requireContext())
            adapter = couponAdapter
            setPadding(0, ScreenUtil.dip(context, 20), 0, 0)
            clipToPadding = false
        }
        with(couponAdapter) {
            showButton = viewModel.status == 0
        }
        couponAdapter.setEmptyView(R.layout.layout_empty_data)
        refreshCollection.setOnRefreshListener { viewModel.couponList(true) }
    }

    override fun initViewModel() {
        viewModel.useType = arguments?.getInt(USE_TYPE) ?: 0
        viewModel.apiType = arguments?.getInt(API_TYPE) ?: 0
        viewModel.status = arguments?.getInt(STATUS) ?: 0
        viewModel.couponListLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshCollection.finishRefresh()
                    else if (it.hasMore) couponAdapter.loadMoreModule?.loadMoreComplete()
                    else couponAdapter.loadMoreModule?.loadMoreEnd(true)
                    // 数据填充
                    if (it.loadMore) couponAdapter.addData(it.data)
                    else couponAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) couponAdapter.loadMoreModule?.loadMoreFail()
                    else refreshCollection.finishRefresh(false)
                }
            }
        })
    }

    /**
     * 自定义布局的对话框
     */
    private fun layDialog(title: String, content: Bitmap?) {
        val view: View = LayoutInflater.from(requireContext()).inflate(
            R.layout.dialog_coupon_qr, null, false
        )
        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
        val tvCouponCode: TextView = view.findViewById(R.id.tvCouponCode)
        val ivCouponQR: ImageView = view.findViewById(R.id.ivCouponQR)
        tvCouponCode.text = title
        if (content == null) {
            ivCouponQR.visibility = View.GONE
            toast("二维码生成错误")
        } else {
            ivCouponQR.visibility = View.VISIBLE
            ivCouponQR.setImageBitmap(content)
        }
        dialog.show()
    }
}